package com.ruoyi.web.controller.mail;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.entity.SysMail;
import com.ruoyi.common.core.domain.entity.SysMailRecord;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.*;


@RestController
@RequestMapping("/mail/info")
public class MailController extends BaseController {

    @Autowired
    MailService mailService;

    private final static String SMTPEmail = "smtp.ym.163.com";// 网易163邮箱的 SMTP 服务器地址


    @PreAuthorize("@ss.hasPermi('mail:info:send')")
    @PutMapping("/send")
    public void sendEmail(@RequestBody SysMail sysMail) throws Exception {
        checkSysEmail(sysMail);
        String cc = sysMail.getCc();
        String content = sysMail.getContent();
        String mailTitle = sysMail.getMailTitle();
        String receiveAddress = sysMail.getReceiveAddress();
        String sendAddress = sysMail.getSendAddress();
        String sendPassword = sysMail.getSendPassword();
        String username = getUsername();
        List<String> receiveAddressList= Arrays.asList(receiveAddress.split(","));
        List<String> ccList = Arrays.asList(cc.split(","));
        //创建连接邮件服务器的参数配置
        Properties props = new Properties();// 参数配置
        props.setProperty("mail.smtp.host", SMTPEmail);// 发件人的邮箱的 SMTP 服务器地址
        props.setProperty("mail.smtp.auth", "true");// 需要请求认证
        props.setProperty("mail.transport.protocol", "smtp");
        //根据配置创建会话对象和邮件服务器交互
        Session session = Session.getInstance(props);
        session.setDebug(true);// 设置为debug模式, 可以查看详细的发送日志
        //创建邮件
        List<MimeMessage> messages = createEmail(username, content, mailTitle, session, sendAddress, receiveAddressList,ccList);
        //使用Session获取邮件传输对象
        Transport transport = session.getTransport();
        //使用邮箱账号和密码连接邮件服务器
        transport.connect(sendAddress, sendPassword);
        //发送邮件
        for (MimeMessage message : messages){
        transport.sendMessage(message, message.getAllRecipients());
        }
        //记录已发数据
        List<SysMailRecord> sysMailRecordList = new ArrayList<>();
        for (String ra : receiveAddressList){
            SysMailRecord sysMailRecord = new SysMailRecord();
            sysMailRecord.setMailTitle(mailTitle);
            sysMailRecord.setReceiveAddress(ra);
            sysMailRecord.setSendAddress(sendAddress);
            sysMailRecord.setSendTime(new Date());
            sysMailRecordList.add(sysMailRecord);
        }
        mailService.insertMailRecord(sysMailRecordList);
        //关闭连接
        transport.close();
    }

    /**
     * 创建邮件
     */
    private static List<MimeMessage> createEmail(String username, String content, String mailTitle, Session session, String sendMail, List<String> receiveMail,List<String> cclist) throws Exception {
        List<MimeMessage> mimeMessagesList = new ArrayList<>();

        for (String s : receiveMail) {
        //创建一封邮件
        MimeMessage emailMessage = new MimeMessage(session);
        //发件人
        emailMessage.setFrom(new InternetAddress(sendMail, username, "UTF-8"));
        //收件人
        //emailMessage.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "XX用户", "UTF-8"));
        emailMessage.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(s, "", "UTF-8"));
        if (cclist!=null){
            emailMessage.addRecipients(MimeMessage.RecipientType.CC,getInternetAddress(cclist));
        }

        //邮件主题
        emailMessage.setSubject(mailTitle, "UTF-8");
        emailMessage.setContent(content, "text/html;charset=UTF-8");
        //设置发件时间
        emailMessage.setSentDate(new Date());
        //保存设置
        emailMessage.saveChanges();
        mimeMessagesList.add(emailMessage);
        }
        return mimeMessagesList;
    }

    public static InternetAddress[] getInternetAddress(List<String> mailList) throws AddressException {
        int length=mailList.size();
        if (length == 0) {
            return null;
        }
        InternetAddress[] internetAddresses = new InternetAddress[length];
        for (int i = 0; i < length; i++) {
            internetAddresses[i]=new InternetAddress(mailList.get(i));
        }
        return internetAddresses;
    }

    private static void checkSysEmail(SysMail sysMail){
        if (StringUtils.isEmpty(sysMail.getSendAddress())){
            throw new ServiceException("发件人不能为空");
        }
        if (StringUtils.isEmpty(sysMail.getReceiveAddress())){
            throw new ServiceException("收件人不能为空");
        }
        if (StringUtils.isEmpty(sysMail.getSendPassword())){
            throw new ServiceException("密码不能为空");
        }
        if (StringUtils.isEmpty(sysMail.getMailTitle())){
            throw new ServiceException("主题不能为空");
        }
    }

    @PreAuthorize("@ss.hasPermi('mail:info:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysMailRecord sysMailRecord) {
        startPage();
        List<SysMailRecord> sysMailRecordList = mailService.selectMailRecordToList(sysMailRecord);
        return getDataTable(sysMailRecordList);
    }
}
